package com.wx.zwxs.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WxService {
    public static final String ACCESS_TOKEN_NAME = "access_token";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${wx.access_token_url}")
    private String access_token_url;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    public String getAccessToken() {
        String access_token = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_NAME);
        if (access_token == null) {
            String url = String.format(access_token_url, appid, secret);
            Map map = restTemplate.getForObject(url, Map.class);
            log.info("调用微信token接口返回信息:" + map.toString());
            access_token = (String) map.get(ACCESS_TOKEN_NAME);
            if (access_token != null) {
                log.info("获取到的access_token：{}", access_token);
                access_token = access_token;
                redisTemplate.opsForValue().set(ACCESS_TOKEN_NAME, access_token, 100, TimeUnit.MINUTES);

            } else {
                return map.toString();
            }
        }
        return access_token;
    }
}
